import { loginAppForWechatCallback } from '@/services/api/api-login';
import { setToken } from '@/utils/token';
import { message, Spin } from 'antd';
import React, { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { history, useModel } from 'umi';

export default (): React.ReactNode => {
  const { initialState, setInitialState } = useModel('@@initialState');
  let location = useLocation();

  const parse = (str = window.location.search) => {
    const reg = /([^?&=]+)=([^&]+)/g; // 分组捕获 两个子组
    const params = {};
    str.replace(reg, (_, k, v) => (params[k] = v));
    return params;
  };

  /** 此方法会跳转到 redirect 参数所在的位置 */
  const goto = () => {
    if (!history) return;

    const search = parse(location.search);

    const { serviceName, code, state } = search as {
      serviceName: string;
      code: string;
      state: string;
    };
    loginAppForWechatCallback({ serviceName, code, state }).then(async ({ code, data }) => {
      if (code === 0) {
        const state = data.state;
        /**
         * 状态
         * 1、无账号
         * 2、有账号，未激活
         * 3、有账号、有激活、未启用
         * 4、有账号、有激活、已启用
         */
        if (state === 1) {
          //无账号
          //跳转到注册页面，注册用户，需要输入手机号、姓名、单位
          history.push(`/user/bind?wechat=${data.wechat}`);
        } else if (state === 2) {
          //有账号，未激活
          //转到登录界面，该账号已完成绑定操作，请等待管理员审核！
          history.push('/user/login');
          message.error('该账号已完成注册或绑定操作，请等待管理员审核！');
        } else if (state === 3) {
          //有账号、有激活、未启用
          //跳转到登录界面，并且提示该账号已经被禁用
          history.push('/user/login');
          message.error('该账号已经被禁用，请联系管理员！');
        } else if (state === 4) {
          //有账号、有激活、已启用
          //正常跳转到主界面
          setToken(data.satoken);
          try {
            const userInfo = await initialState?.fetchUserInfo?.();
            if (userInfo) {
              setInitialState({
                ...initialState,
                currentUser: userInfo,
              });
            }
            setTimeout(() => {
              history.push('/');
            }, 300);
          } catch (error) {
            history.push('/user/login');
          }
        } else if (state === 5) {
          //选择登录
          history.push('/user/select?accountId=' + data.accountId);
        }
      } else {
        history.push('/user/login');
      }
    });
  };

  useEffect(() => {
    goto();
  }, []);

  return (
    <div
      style={{
        textAlign: 'center',
        marginTop: 100,
        marginBottom: 20,
      }}
    >
      <div>
        <img src="/logo.png" alt="logo" width="256" />
      </div>
      <Spin
        style={{
          marginTop: 50,
        }}
        size="large"
      />
      <div
        style={{
          marginTop: 50,
          fontSize: '1.1rem',
        }}
      >
        登录中，正在加载资源...
      </div>
      <div
        style={{
          marginTop: 20,
          fontSize: '1rem',
          color: '#888',
        }}
      >
        初次加载资源可能需要较多时间 请耐心等待
      </div>
    </div>
  );
};
